using UnityEditor;
using UnityEngine;
using System.IO;
using System;

public class LevelAssetCreator : EditorWindow
{
    private MonoScript levelScript;
    private DefaultAsset targetFolder;
    private string customFileName = "SO Name";

    [MenuItem("Tools/SO Asset")]
    public static void ShowWindow()
    {
        GetWindow<LevelAssetCreator>("Create SO Asset");
    }

    void OnGUI()
    {
        GUILayout.Label("SO Asset Creator", EditorStyles.boldLabel);
        EditorGUILayout.Space();

        // 拖拽脚本区域
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        GUILayout.Label("Drag & Drop SO Script", EditorStyles.boldLabel);
        levelScript = (MonoScript)EditorGUILayout.ObjectField(
            levelScript,
            typeof(MonoScript),
            false);
        EditorGUILayout.EndVertical();

        EditorGUILayout.Space();

        // 目标文件夹选择
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Save Folder", GUILayout.Width(80));
        targetFolder = (DefaultAsset)EditorGUILayout.ObjectField(
            targetFolder,
            typeof(DefaultAsset),
            false);

        if (GUILayout.Button("Browse", GUILayout.Width(60)))
        {
            string path = EditorUtility.OpenFolderPanel("Select Save Folder", "Assets", "");
            if (!string.IsNullOrEmpty(path))
            {
                if (path.StartsWith(Application.dataPath))
                {
                    path = "Assets" + path.Substring(Application.dataPath.Length);
                    targetFolder = AssetDatabase.LoadAssetAtPath<DefaultAsset>(path);
                }
            }
        }
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.Space();

        // 自定义文件名
        GUILayout.Label("Asset Name", EditorStyles.boldLabel);
        customFileName = EditorGUILayout.TextField("File Name", customFileName);

        EditorGUILayout.Space();

        // 创建按钮
        GUI.enabled = levelScript != null && targetFolder != null && !string.IsNullOrWhiteSpace(customFileName);
        if (GUILayout.Button("Create SO Asset", GUILayout.Height(30)))
        {
            CreateLevelAsset();
        }
        GUI.enabled = true;
    }

    void CreateLevelAsset()
    {
        try
        {
            // 获取脚本类型
            System.Type scriptType = levelScript.GetClass();

            // 验证脚本类型
            if (scriptType == null || !scriptType.IsSubclassOf(typeof(ScriptableObject)))
            {
                Debug.LogError("Selected script is not a valid ScriptableObject type!");
                return;
            }

            // 创建实例
            ScriptableObject levelAsset = ScriptableObject.CreateInstance(scriptType);

            // 获取保存路径
            string folderPath = AssetDatabase.GetAssetPath(targetFolder);
            string assetPath = Path.Combine(folderPath, $"{customFileName}.asset");
            assetPath = AssetDatabase.GenerateUniqueAssetPath(assetPath);

            // 保存资产
            AssetDatabase.CreateAsset(levelAsset, assetPath);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();

            // 选中新创建的资产
            EditorUtility.FocusProjectWindow();
            Selection.activeObject = levelAsset;

            Debug.Log($"Created new SO asset at: {assetPath}");
        }
        catch (Exception e)
        {
            Debug.LogError($"Failed to create asset: {e.Message}");
        }
    }
}